const { ethers } = require('ethers');

async function getSign() {
  // 连接到以太坊网络
  const provider = new ethers.providers.JsonRpcProvider('https://ropsten.infura.io/v3/YOUR_INFURA_PROJECT_ID');
  // 设置私钥
  const privateKey = 'fec4de8b60d3f9ef0003fc4143d2675eb6c3dbced35633e8aa7854abbe8e0459';

  const list = [
    ethers.BigNumber.from(36),
    ethers.BigNumber.from(69),
    ethers.BigNumber.from(555)
  ];
  const address = '0x21e35e6e68E465C96e0186a8FeEE356aD9A79Ee3';
  //const dataString = '0xabcdef123456';
  const dataString = '这是一个中文字符串';

  // 设置参数值
  const num = ethers.BigNumber.from(123);
  // 构建要签名的数据
  const encodedNum = ethers.utils.hexZeroPad(ethers.utils.hexlify(num), 32);

  // 将integer类型的数组转换为字节数组
  let byteList = [];
  for (let i = 0; i < list.length; i++) {
    const paddedBytes = ethers.utils.hexZeroPad(ethers.utils.hexlify(list[i]), 32);
    byteList = byteList.concat(ethers.utils.arrayify(paddedBytes));
  }
  const encodedList = Uint8Array.from(byteList);

  const encodedAddress = ethers.utils.arrayify(address);// Buffer.from(address.slice(2), 'hex');
  //const encodedDataString = ethers.utils.arrayify(dataString);//这里是16进制字符串
  const encodedDataString = new TextEncoder().encode(dataString);

  const message = ethers.utils.concat([encodedNum, encodedList, encodedAddress, encodedDataString]);

  // 对合并后的字节码进行keccak256哈希
  const hash = ethers.utils.keccak256(message);
  // 使用私钥签名消息
  const wallet = new ethers.Wallet(privateKey, provider);
  const signature = await wallet.signMessage(ethers.utils.arrayify(hash));
  const signResult = signatureToHex(signature);
  // 打印签名结果
  console.log('Signature: ' + signResult);

  let recoveredAddress = ethers.utils.recoverAddress(hash, signature);
  console.log('Recovered address:', recoveredAddress);
}
function signatureToHex(signature) {
  const { r, s, v } = ethers.utils.splitSignature(signature);
  return '0x' + r.slice(2) + s.slice(2) + v.toString(16);
}
getSign().catch(console.error);